# -*-coding:utf-8-*-

from tests.apis.http import *
from tests.apis.base import BaseAPI
import urllib


class Orders(BaseAPI):
    def __init__(self, *args, **kwargs):
        super(Orders, self).__init__(*args, **kwargs)

    def create_order(self, *args, **kwargs):
        response = http_post('platform/api/orders', kwargs, self.query)
        return self.assert_response_success_data(response, **kwargs)

    def delete_order(self, *args, **kwargs):
        order_id = kwargs['order_id']
        response = http_delete('platform/api/orders/%s' % order_id, query=self.query)
        return self.assert_response_success_data(response)

    def update_order(self, *args, **kwargs):
        order_id = kwargs.pop('order_id')
        response = http_put('platform/api/orders/%s' % order_id, kwargs, query=self.query)
        return self.assert_response_success_data(response)

    def update_order_status(self, *args, **kwargs):
        order_id = kwargs.pop('order_id')
        response = http_put('platform/api/orders/%s/status' % order_id, kwargs, query=self.query)
        return self.assert_response_success_data(response)

    def get_order(self, *args, **kwargs):
        order_id = kwargs.pop('order_id')
        response = http_get('platform/api/orders/%s' % order_id, query=self.query)
        return self.assert_response_success_data(response)

    def get_order_list(self, *args, **kwargs):
        return self._get_order_list(**kwargs)

    def get_order_count(self, *args, **kwargs):
        return self._get_order_list(get_count=True, **kwargs)

    def get_order_commissions(self, *args, **kwargs):
        query = 'aspect=commissions&%s' % self.query
        response = http_get('platform/api/orders/statistics', query=query)
        return self.assert_response_success_data(response)

    def get_order_statistics(self, *args, **kwargs):
        query = self.query_from_kwargs(**kwargs)
        response = http_get('platform/api/orders/statistics', query=query)
        return self.assert_response_success_data(response)

    def _get_order_list(self, get_count=False, **kwargs):
        query = self.query_from_kwargs(**kwargs)
        url = 'platform/api/orders'
        if get_count:
            url += '/count'
        response = http_get(url, query)
        return self.assert_response_success_data(response)

    def get_order_wx_pay_prepay(self, *args, **kwargs):
        oid = kwargs.pop('oid')
        qs = urllib.urlencode(kwargs)
        query = self.query
        if 0 < len(qs):
            query += '&%s' % qs
        response = http_get('platform/api/orders/%s/wx/pay/prepay' % oid, query=query)
        return self.assert_response_success_data(response)
